package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.management.Query;

@Slf4j
@AllArgsConstructor // 全参
@NoArgsConstructor // 无参
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {



    private SubjectMapper subjectMapper;

    // 遍历每一行记录
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext context) {


        System.out.println(data);

        //读取出来的数据
        String levelOneTitle = data.getLevelOneTitle();//一级标题
        String levelTwoTitle = data.getLevelTwoTitle();//二级标题

        //根据levelOneTitle判断类别是否重复
        Subject subjectlevelOne = this.getByTitle(levelOneTitle);
        String parentId = null;
        if (this.getByTitle(levelOneTitle)==null){
            //不重复，则将一些类别存入数据库，得到一级类别的id
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            subjectMapper.insert(subject);
            parentId = subject.getId();
        }else{
            //重复则不插入，则将id取出
            parentId = subjectlevelOne.getId();
        }
        //根据levelTwoTitle和parentId判断二级类别是否重复
        Subject subjectLevelTwo = this.getSubByTitle(levelTwoTitle, parentId);
        if (subjectLevelTwo == null){
            Subject subject = new Subject();
            subject.setParentId(parentId);
            subject.setTitle(levelTwoTitle);
            subjectMapper.insert(subject);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("数据解析完成");
    }

    /**
     * 判断一级类别是否重复
     * @param title 类别名称
     * @return 如果重复则返回找到对象，如果不重复则返回null
     */
    private Subject getByTitle(String title){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        return subjectMapper.selectOne(queryWrapper);
    }

    /**
     * 判断二级类别是否重复
     * @param title 类别名称
     * @param title 父类别id
     * @return 如果重复则返回找到对象，如果不重复则返回null
     */
    private Subject getSubByTitle(String title,String parenId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",parenId);
        return subjectMapper.selectOne(queryWrapper);
    }



}
